<template>
  <div id="whole">
    <!-- {{this.zoologyWK}} -->
    <!-- {{this.search_WK_req}} -->
    <!-- {{this.search_WK_resp}} -->
    <!-- {{this.isCheck}} -->
    <!-- {{this.details_table}} -->
    <!-- {{this.aimLine}} -->
    <!-- {{this.soilWK}} -->
    <!-- {{this.heatJson}} -->
    <div id="container" style="width: 100%; height: 100%; position: relative" >
        <el-tooltip placement="bottom" content="查询样本点">
            <div class="option_buttons" style="top:25%;right:2%;"  @click="search_WK_open" >
                <div style="height: 45px; width: 45px;align-content:center;text-align:center;">
                    <i class="iconfont ali-tiaochadian" style="font-size:30px"></i>
                </div>
            </div>
        </el-tooltip>
        <el-tooltip placement="bottom" content="样本点调查数据">
            <div class="option_buttons" style="top:55%;right:2%;"  @click="details_box_open" >
                <div style="height: 45px; width: 45px;align-content:center;text-align:center;">
                    <i class="iconfont ali-xiangqing" style="font-size:30px"></i>
                </div>
            </div>
        </el-tooltip>
        <div ref="pop_box" style="display:flex;flex-direction:column;;position:absolute;z-index:10;background-color:white;width:360px;height:320px;" v-if="false">
            <div style="background-color:white;flex:0 0 10%;align-content:center;position:relative;">
                <i class="el-icon-info" style="margin-left:5px;margin-right:5px;border-bottom:1px solid black"></i>
                <span style="font-weight:bold;">{{box_data.title}}-采样点信息</span>
                <i class="el-icon-close" style="position:absolute;right:5%;" @click="overlay.setPosition(undefined)"></i>
            </div>
            <div style="flex:1;display:flex;box-shadow: 5px 5px 15px rgba(0, 0, 0.5);">
                <el-descriptions :column="1" border style="padding:5px;border-radius: 8px">
                    <el-descriptions-item>
                    <template slot="label">
                        样点编号
                    </template>
                        {{box_data.id_sample}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        区县：
                    </template>
                        {{box_data.county}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        乡镇：
                    </template>
                        {{box_data.town}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        经度：
                    </template>
                        {{box_data.latitude}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        纬度：
                    </template>
                        {{box_data.longitude}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        时间：
                    </template>
                        {{box_data.time}}
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </div>
        <div v-if="details_box_show" class="WK_search_box" style="background-color:white;width:1000px;height:600px;left:20%;">
            <div style="flex:0 0 6%;background-color:#959da9;align-content:center;position:relative;;">
                <i class="el-icon-search" style="margin-left:5px;"></i>
                <span style="color:white;margin-left:5px;">生物专题信息</span>
                <div class="el-icon-close" style="margin-left:300px;position:absolute;right:5%;" @click="details_box_close"></div>
            </div>
            <div>
                <el-table :data="details_table" max-height="560px" :row-class-name="tableAimLineClass" ref="detailTable">
                        <el-table-column
                            prop="id"
                            fixed
                            label="序号"
                            width="80">
                        </el-table-column>
                        <el-table-column
                            prop="county"
                            fixed
                            label="区县"
                            width="100">
                        </el-table-column>
                        <el-table-column
                            prop="id_sample"
                            fixed
                            label="采样点编号"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="name_repair"
                            label="修复区名称"
                            width="175">
                        </el-table-column>
                        <el-table-column
                            prop="number_plot"
                            label="样方数量"
                            width="80">
                        </el-table-column>
                        <el-table-column
                            prop="number_altitude_zone"
                            label="高程分带数量"
                            width="130">
                        </el-table-column>
                        <el-table-column
                            prop="name_community"
                            label="植被类型"
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="dominate_species"
                            label="优势物种"
                            width="180">
                        </el-table-column>
                        <el-table-column
                            prop="fcover"
                            label="群落覆盖度"
                            width="130">
                        </el-table-column>
                        <el-table-column
                            prop="above_biomass"
                            label="群落干生物量"
                            width="130">
                        </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="WK_search_box" style="display:flex;flex-direction:column;" v-if="search_WK_show">
            <div style="flex:0 0 6%;background-color:#959da9;align-content:center;position:relative;;">
                <i class="el-icon-search" style="margin-left:5px;"></i>
                <span style="color:white;margin-left:5px;">生物专题采样点查询</span>
                <div class="el-icon-close" style="margin-left:300px;position:absolute;right:5%;" @click="search_WK_show=false;"></div>
            </div>
            <div style="flex:1;display:flex; flex-direction:column;">
                <div style="flex:0 0 20%;position:relative;">
                    <el-form id='search_title' :model="search_WK_req">
                        <el-row style="margin-top:20px;">
                            <el-col :span="12">
                                <el-form-item label="行政区划（区/县）" class="first_column" label-width='180px'>
                                    <el-select v-model="search_WK_req.county" size="mini" style="width:180px;">
                                        <el-option
                                        v-for="item in search_WK_options.county"
                                        :key="item.label"
                                        :label="item.label"
                                        :value="item.label"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="调查时间" label-width="100px">
                                    <el-select v-model="search_WK_req.time"
                                    size="mini"
                                    multiple
                                    collapse-tags
                                    style="width:160px;"
                                    >
                                        <el-option
                                        v-for="item in search_WK_options.time"
                                        :key="item.label"
                                        :label="item.label"
                                        :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="参数范围选择" label-width="130px">
                                    <el-select v-model="search_WK_req.geologyNums"
                                    size="mini"
                                    collapse-tags
                                    style="width:160px;"
                                    >
                                        <el-option
                                        v-for="item in search_WK_options.geologyNums"
                                        :key="item.label"
                                        :label="item.label"
                                        :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="3">
                                <el-form-item label-width="30px">
                                    <el-select v-model="search_WK_req.chars"
                                    size="mini"
                                    collapse-tags
                                    style="width:60px;"
                                    placeholder=""
                                    :disabled="isCheck"
                                    >
                                        <el-option
                                        v-for="item in search_WK_options.chars"
                                        :key="item.label"
                                        :label="item.label"
                                        :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-form-item label-width="30px">
                                    <el-input style="height:50px" :disabled="isCheck" v-model="search_WK_req.nums"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="3" :offset="1">
                                <el-button @click="search_WK_ok">查询</el-button>
                            </el-col>
                            <el-col :span="3">
                                <el-button @click="search_WK_reset">重置</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div style="flex:1;">
                    <el-table :data="search_WK_resp" max-height="400px">
                        <el-table-column
                            prop="id"
                            label="序号"
                            width="80">
                        </el-table-column>
                        <el-table-column
                            prop="county"
                            label="区县"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="town"
                            label="乡镇"
                            width="150">
                        </el-table-column>
                        <el-table-column
                            prop="latitude"
                            label="纬度"
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="longitude"
                            label="经度"
                            width="110">
                        </el-table-column>
                        <el-table-column
                            prop="id_sample"
                            label="采样点编号"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="time"
                            label="时间"
                            width="100">
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script type="text/javascript" src='//webapi.amap.com/maps?v=2.0&key=8b9c8c5786f7ee7871906d9700229056'></script>
<script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>

<script>
import Axios from '@/my_axios';
import {treeList} from '@/assets/common';

import {Feature, Map, View} from 'ol';
import {fromLonLat, toLonLat} from 'ol/proj';

import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import HeatmapLayer from 'ol/layer/Heatmap';


import XYZ from 'ol/source/XYZ';
import VectorSource from 'ol/source/Vector';

import GeoJSON from 'ol/format/GeoJSON';
import {Style, Fill, Stroke, Circle, Icon} from 'ol/style';

import Point from 'ol/geom/Point';
import Overlay from 'ol/Overlay';


export default {
    name: "mapVue",
    async mounted() {
        // detail_table
        Axios.post("getzoologywkPro")
        .then((resp)=> {
            // console.log('.....', resp);
            this.details_table = resp.data.data;
        })

        await this.getZoologyWK();
        this.initAMap();
        this.$nextTick(()=> {
            this.initMaket();
        })
    },
    unmounted() {
        this.map?.destroy();
    },
    data: function () {
        return {
            id_tst: 234,
            AMap: null,
            map: null,
            geocoder: null,
            select_one: null,

            // layers
            qxLayer:null,
            zoologyLayer:null,

            //fetch_statistic
            soilWK:null,

            // point details 
            box_data: {},

            // details_box
            details_box_show:false,
            details_table:[],

            // search_WK
            search_WK_show:false,
            search_WK_req:{
                'title':'zoology',
                'geologyNums':''
            },
            isCheck: false,
            search_WK_options:{
                county:[],
                time:[
                    {
                        label: '2021/04',
                        value: '2021/04',
                    },
                    {
                        label: '2021/08',
                        value: '2021/08',
                    },
                    {
                        label: '2022/04',
                        value: '2022/04',
                    },
                    {
                        label: '2022/06',
                        value: '2022/06',
                    },
                    {
                        label: '2022/08',
                        value: '2022/08',
                    },
                ],
                geologyNums: [
                    {
                        label: '群落覆盖度',
                        value: 'fcover'
                    },
                    {
                        label: '群落干生物量',
                        value: 'above_biomass'
                    },
                ],
                chars: [
                    {
                        label: '≥',
                        value: 'bigger'
                    },
                    {
                        label: '<',
                        value: 'smaller'
                    },
                ]
            },//选项数据
            search_WK_resp:[],

            aimLine: "",
        };
    },
    watch: {
        search_WK_resp() {
            // 目前：search到的所有点
            const tmp = []
            this.search_WK_resp.forEach((element)=> {
                tmp.push(element.id_sample)
            })
        },
        search_WK_req: {
            handler(newVal) {
                if(this.search_WK_req.geologyNums==''){
                    this.isCheck = true
                }else{
                    this.isCheck = false
                }
            },
            deep: true

        }
    },
    methods: {
        initAMap() {
            var tianditu_token = '816cded7027c0dd4de266ef32a030a19'
            this.map = new Map({
                target: 'container',
                view: new View({
                    projection: 'EPSG:3857',
                    center: fromLonLat([109, 30]),
                    // center: fromLonLat([0, 0]),
                    zoom: 8.3,
                }),
            });

            this.yxLayer = new TileLayer({
                name: 'tianditu_yx',
                zIndex:1,
                source: new XYZ({
                    url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + tianditu_token,
                    wrapX: false
                })
            }),
            this.map.addLayer(this.yxLayer);

            this.yxmLayer = new TileLayer({
                name: 'tianditu_yxm',
                zIndex:3,
                source: new XYZ({
                    url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + tianditu_token,
                    wrapX: false
                })
            }),
            this.map.addLayer(this.yxmLayer);


            this.qxLayer = new VectorLayer({
                name: 'qx',
                zIndex:2,
                source: new VectorSource({
                    url: '/geoDatas/qx.json',
                    format: new GeoJSON(),
                }),
                style: this.getDefaultStyle,
            });
            this.map.addLayer(this.qxLayer);

            this.zoologyLayer = new VectorLayer({
                name:'zoology',
                zIndex:21,
                source: new VectorSource()
            });
            // this.map.addLayer(this.zoologyLayer);

            // for dialog
            this.overlay = new Overlay({
                name:'mark',
                zIndex:9,
                element: this.$refs.pop_box,
                positioning: 'bottom-center',
                stopEvent: false,
            });

            // this.map.addOverlay(this.overlay);

            this.map.on('click', (e)=> {
                // console.log("点击事件：", e.coordinate)
                const feature = this.map.forEachFeatureAtPixel(e.pixel, (feature)=> {
                    return feature;
                })
                if(feature && feature.getGeometry() instanceof Point) {
                    // console.log("点击了:", feature.getKeys());
                    // console.log("点击了:", feature.get('id_sample'), feature);//tmd, 必须为get才能取到; 然后就可以用this.GeoWK来取得对应WK的详细数据

                    let id_sample = feature.get('id_sample');
                    this.aimLine = id_sample
                    this.scrollToRow(id_sample) // 触发滚动
                }
            })

            // 热力图
            // 创建热力图数据源
            // console.log('!!!!1:', this.soilWK[0].longitude, this.soilWK[0].latitude, this.soilWK[0].fcover)
            // console.log('!!!!2:', typeof(parseFloat(this.soilWK[0].longitude)), typeof(parseFloat(this.soilWK[0].latitude)))

            const features = this.soilWK.map(item => {
                const feature = new Feature({
                    geometry: new Point(
                        fromLonLat([parseFloat(item.longitude), parseFloat(item.latitude)])
                    ),
                    weight: item.fcover / 10, // 将值标准化到 0-1 范围
                    id: item.id,
                    id_sample: item.id_sample
                })
                return feature
            })

            const vectorSource = new VectorSource({
                features: features
            })



            // 创建热力图层
            const heatmapLayer = new HeatmapLayer({
                name:'heat',
                source: vectorSource,
                zIndex: 20,
                blur: 40,       // 模糊尺寸
                radius: 20,      // 热力点半径
                weight: 'weight', // 使用feature的weight属性
                gradient: [
                    'rgba(0,0,255,0)',    // 透明蓝
                    'rgba(0,255,255,0.6)', // 青色
                    'rgba(0,255,0,0.8)',   // 绿色
                    'rgba(255,255,0,0.9)', // 黄色
                    'rgba(255,0,0,1)'      // 红色
                ],
            })
            this.map.addLayer(heatmapLayer)

            // 根据缩放级别动态调整半径
            this.map.getView().on('change:resolution', () => {
                const zoom = this.map.getView().getZoom()
                heatmapLayer.setRadius(Math.max(15, 30 - zoom * 2))
            })

        },

        // 其他方法
        test() {
            console.log("*****test********");
            this.zoologyLayer.getSource().clear();

        },
        tableAimLineClass(row) {
            // console.log(row.row.id_sample)
            // console.log(row.id_sample)
            if(row.row.id_sample == this.aimLine){
                return 'tr-red';
            }
            return '';
        },
        scrollToRow(id_sample) {
            // 滚动到指定行（带平滑动画）
            this.details_box_show = true

            const index = this.details_table.findIndex(item => item.id_sample === id_sample)
            if (index === -1) return

            // 确保表格已渲染
            this.$nextTick(() => {
                // 获取表格的滚动容器
                const tableBodyWrapper = this.$refs.detailTable.$el.querySelector('.el-table__body-wrapper')
                if (!tableBodyWrapper) return

                // 获取所有行元素
                const rows = tableBodyWrapper.querySelectorAll('.el-table__row')
                if (!rows || index >= rows.length) return

                // 计算目标行位置
                const targetRow = rows[index]
                const rowTop = targetRow.offsetTop
                const rowHeight = targetRow.offsetHeight
                const containerHeight = tableBodyWrapper.clientHeight

                // 计算居中滚动位置
                const scrollTop = rowTop - (containerHeight / 2) + (rowHeight / 2)

                // 平滑滚动实现
                if ('scrollBehavior' in document.documentElement.style) {
                    tableBodyWrapper.scrollTo({
                        top: scrollTop,
                        behavior: 'smooth'
                    })
                } else {
                    tableBodyWrapper.scrollTop = scrollTop
                }
            })
        },
        getDefaultStyle(feature){
            const name = feature.get('NAME99');

            const isHightlighted = (name === this.select_one);
            // console.log('--------------------------------', isHightlighted)
            return new Style({
                fill: new Fill({
                    color: isHightlighted? 'rgba(255, 0, 0, 0.6)' : 'rgba(58, 175, 205, 0.8)'
                }),
                stroke: new Stroke({
                    color: 'black',
                    width: 1
                })
            })
        },
        // 传入位置（地理坐标or城市编号），然后将当前地图中心聚焦于此地并设置合适的缩放比例
        focus_on(location, done) {
            // console.log('!!!!!!!!!!!!!', location)
            var view = this.map.getView()
            location = fromLonLat(location)
            // tmp.setCenter(fromLonLat(center));
            // https://openlayers.org/en/latest/examples/animation.html
            const duration = 2000;
            const zoom = view.getZoom();
            let parts = 2;
            let called = false;
            function callback(complete) {
                --parts;
                if (called) {
                return;
                }
                if (parts === 0 || !complete) {
                called = true;
                done(complete);
                }
            }
            view.animate(
                {
                center: location,
                duration: duration,
                },
                callback,
            );
            view.animate(
                {
                zoom: zoom - 1,
                duration: duration / 2,
                },
                {
                zoom: zoom,
                duration: duration / 2,
                },
                callback,
            );
        },
        navi_click(data) {
            this.select_one = data.label;
            this.qxLayer.setStyle(this.getDefaultStyle);
            //focus_on
            this.focus_on(data.lng, function(){})
        },
        addMarker(source, latitude, longitude, name, index, title) {
            const corordinate = fromLonLat([longitude,latitude]);
            const point = new Point(corordinate);

            const market = new Feature({
                geometry: point,
                name: name,
                index: index,
                title: title, //为了后面弹出框的信息能够 区分两者的数据来源
            });

            market.setStyle(
                new Style({
                    image: new Icon({
                        src: '/workpoint/tb_zoology_workpoint/swSample.png',
                        scale: 0.4
                    }),
                })
            );

            source.addFeature(market);
        },
        async getZoologyWK() {
            await Axios.post('/get_zoologyworkpoints')
            .then((resp)=>{
                // console.log(resp.data.data)
                this.soilWK = resp.data.data
            }).catch((e)=>{
                console.log(e)
            })
        },
        initMaket() {
            this.soilWK.forEach((element, index) => {
                // console.log('element', element)
                this.addMarker(this.zoologyLayer.getSource(), element.latitude, element.longitude,element.county, index, '生物专题')//获取点击位置
            });
        },
        search_WK_open() {
            if(this.search_WK_options.county.length==0)
                treeList.children.forEach((element)=> {
                    this.search_WK_options.county.push(element);
                })

            this.search_WK_show = this.search_WK_show?false:true;
        },
        search_WK_ok() {
            if(!this.search_WK_req.county||!this.search_WK_req.time){
                // console.log('enter1')
                window.alert('查询参数不完整!')
                return
            }
            if(this.search_WK_req.geologyNums && (!this.search_WK_req.chars||!this.search_WK_req.nums)){
                // console.log('enter1')
                window.alert('查询参数不完整!')
                return
            }else{
                console.log('enter2')
            }
            Axios.post('/search_WK', {
                search_WK_req:this.search_WK_req
            }).then((resp)=> {
                // console.log('resp:', resp)
                this.search_WK_resp = resp.data.data;
                this.zoologyLayer.getSource().clear();
                this.search_WK_resp.forEach((element, index)=> {
                    // console.log('........', element)
                    this.addMarker(this.zoologyLayer.getSource(), element.latitude, element.longitude,element.county, index, '生物专题')//获取点击位置
                })
            })
        },
        search_WK_reset() {
            this.search_WK_req = {"title":'zoology', 'geologyNums':''};
            this.search_WK_resp = [];
        },
        details_box_open() {
            // console.log('enter')
            this.details_box_show = this.details_box_show?false:true;
        },
        details_box_close() {
            this.details_box_show = false
            this.aimLine = ''
        }
    },
};
</script>

<style scoped>
.box_column {
    flex: 0 0 14%;
    /* border: 1px solid black; */
    align-content: center;
    text-align: center;
}
.title_choice {
    width:160px;
    height: 60px;
    margin:3px;
    background-color: green;
    align-content: center;
    /* color:white; */
    /* background-image: url('../../public/turang.jpeg'); */
}
.title_choice /deep/ .el-radio__label {
    color: white;
}

.option_buttons {
    position: absolute;
    z-index: 10;
    background-color: white;
    border: 2px solid grey;
}


.option_buttons:hover{
    background-color: orange;
}

.WK_search_box {
    width:800px;
    height: 600px;
    z-index:11;
    background-color:white;
    position:absolute;
    top:5%;
    left:20%;
    box-shadow: 5px 5px 15px rgba(0, 0, 0.5);
    border: 2px solid #999;
    display: flex;
    flex-direction: column;
}

::v-deep .el-descriptions {
    width:100%;
}

::v-deep .el-table .tr-red {
    font-weight: bold;
    background: #f0f9eb !important;
    transition: background 0.3s;
}

/* 平滑滚动支持 */
.el-table__body-wrapper {
  scroll-behavior: smooth;
}
</style>
